package com.example.todolist.service;

import com.example.todolist.entity.ReviewTask;
import com.example.todolist.mapper.ReviewTaskMapper;
import com.example.todolist.tools.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.List;

@Service
public class ReviewTaskService {
    @Autowired
    private ReviewTaskMapper reviewTaskMapper;
    @Autowired
    private TaskEachDayService taskEachDayService;
    public ResponseBody<List<ReviewTask>> getOneDayTask(Integer userId, Date date)
    {
        return new ResponseBody<>(200,"success",reviewTaskMapper.getOneDayTask(userId,date));
    }
    public ResponseBody<Integer> addReviewTask(ReviewTask reviewTask,Date beginDate,Date endDate)
    {
        long []day1 = {1,2,4,7,15,30,90,120};
        long []day2 = {1,3,7,11,21};
        for(int i=0;i<8;i++)
        {
            Date newDate= new Date(beginDate.getTime()+day1[i]*1000*60*60*24);
            if(newDate.getTime()>endDate.getTime())
            {
                break;
            }
            reviewTaskMapper.addReviewTask(reviewTask.getUserId(),reviewTask.getTaskName(),newDate,reviewTask.getDescription(),reviewTask.getTaskType());
        }
        for(int i=0;i<5;i++)
        {
            Date newDate= new Date(endDate.getTime()-day2[i]*1000*60*60*24);
            if(newDate.getTime()<beginDate.getTime())
            {
                break;
            }
            int p=reviewTaskMapper.checkIfTaskExist(reviewTask.getUserId(),newDate,reviewTask.getTaskName());
            if(p==0)
                reviewTaskMapper.addReviewTask(reviewTask.getUserId(),reviewTask.getTaskName(),newDate,reviewTask.getDescription(),reviewTask.getTaskType());
        }
        return new ResponseBody<>(200,"success",1);
    }

    public ResponseBody<Integer> deleteOneTask(Integer userId, Date date) {
        reviewTaskMapper.deleteOneTask(userId,date);
        return new ResponseBody<>(200,"success",1);
    }

    public ResponseBody<Integer> checkForReviewTask(Integer userId, Date date, String taskName) {
        ReviewTask reviewTask = reviewTaskMapper.getOneReviewTask(userId, date, taskName);
        if(reviewTask.getTaskDone().equals(0)) {
            reviewTaskMapper.checkForTask(userId, date, taskName);
            taskEachDayService.updateTaskEachDay(userId);
            return new ResponseBody<>(200, "打卡成功", 1);
        }
        else
        {
            reviewTaskMapper.resetForTask(userId,date,taskName);
            taskEachDayService.deleteTaskEachDay(userId);
            return new ResponseBody<>(200,"取消成功",1);
        }
    }
}
